package com.huo.getphonenumber;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huo on 22/11/2016.
 */

public class GetPhoneInfo {

    private static Cursor cursor;

    public static List<ContactsInfo> getContactsInfo(Context context) {

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions((Activity) context,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else{
            cursor = context.getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        }

        List<ContactsInfo> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
            String number = cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER));
            ContactsInfo info = new ContactsInfo(name, number);
            list.add(info);
        }
        cursor.close();
        return list;
    }
}
